package com.example.shopdemo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-19
 **/
@Slf4j
public class FileUtil {


    private static String seperator = System.getProperty("file.separator");
    private static final Random r = new Random();
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    public static String getImgBasePath() {
        String os = System.getProperty("os.name");
        String basePath = "";
        if(os.toLowerCase().startsWith("win")) {
            basePath = "D:/image";
        } else {
            basePath = "/Users/xuwanying";
        }
        basePath = basePath.replace("/",seperator);
        return basePath;

    }
    public static String getShopImagePath(long shopId){
        StringBuilder shopImagePathBuilder = new StringBuilder();
        shopImagePathBuilder.append("/upload/images/item/shop");
        shopImagePathBuilder.append(shopId);
        shopImagePathBuilder.append("/");
        String shopImagePath = shopImagePathBuilder.toString().replace("/",seperator);
        return shopImagePath;
    }

    public static String getRandomFileName() {
        //生成随机文件名，当前年月日时分秒+五位随机数
        int randomRum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000;
        LocalDateTime now = LocalDateTime.now();
        String nowTimeStr = LocalDateTime2String(now);
        return nowTimeStr+randomRum;

    }

    public static  String LocalDateTime2String(LocalDateTime dateTime){
       return   dateTime.format(dateTimeFormatter);
    }

    /**
     * storePath是文件路径还是目录路径
     * 如果storePath是文件路径则删除该文件
     * 如果storePath是目录路径则删除该文件夹下所有文件
     * @param storePath
     */
    public static void deleteFile(String storePath){
        log.info("删除文件:{}",storePath);
        File file = new File(getImgBasePath()+storePath);
        if(file.exists()){
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for(int i=0;i<files.length;i++){
                    files[i].delete();
                }
            }
            file.delete();
        }
    }
}
